package com.hefan.oms.service;

import com.alibaba.fastjson.JSON;
import com.cat.common.entity.ResultBean;
import com.cat.common.meta.ImCustomMsgEnum;
import com.cat.common.meta.ResultCode;
import com.cat.tiger.util.GlobalConstants;
import com.hefan.common.exception.DataIllegalException;
import com.hefan.oms.bean.RebalanceVo;
import com.hefan.oms.itf.AccountService;
import com.hefan.oms.itf.ExpendService;
import com.hefan.oms.itf.InComeService;
import com.hefan.oms.itf.MessageService;
import com.hefan.user.bean.UserLevelChangeVo;
import com.hefan.user.bean.WebUser;
import com.hefan.user.itf.WebUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 账目明细记录
 *
 * @author wangchao
 * @create 2016/11/4 10:23
 */
@Component("accountService")
public class AccountServiceImpl implements AccountService {

  private Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);
  @Resource
  private WebUserService webUserService;
  @Resource
  private InComeService inComeService;
  @Resource
  private ExpendService expendService;
  @Resource
  private MessageService privateMessageService;

  /**
   * 记录用户消费明细、升级IM，明星收入明细、统计月收入、直播收入等
   *
   * @param rebalanceVo
   * @param webUser
   * @throws Exception
   */
  @Override
  @Deprecated
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void rebalanceLivePresent(RebalanceVo rebalanceVo) throws Exception {
/*    if (rebalanceVo == null) {
      logger.error("参数错误rebalanceVo为空");
      return;
    }
    WebUser webUser = webUserService.getWebUserInfoByUserId(rebalanceVo.getFromId());
    if (webUser == null) {
      logger.error("参数错误webUser为空={}", rebalanceVo.getFromId());
      return;
    }
    int fanPiaoNum = Double.valueOf(rebalanceVo.getPrice()).intValue();
    //饭票兑换盒饭
    int hefanNum = currencyExchangeService.exchangeFanPiao2HeFan(fanPiaoNum, GlobalConstants.EX_RULE_FANPIAO_HEFAN);
    inComeService.saveWebIncome(rebalanceVo, hefanNum);
    expendService.saveExpend(rebalanceVo, fanPiaoNum);
    logger.info ("处理用户UserId{}经验信息",webUser.getUserId());
    dealAccountExp(rebalanceVo,webUser);
    dealAnchorDetail(rebalanceVo, hefanNum, webUser);*/
  }

  @Override
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void dealAccountExp(RebalanceVo rebalanceVo, WebUser webUser) throws Exception {
    //非网红，明星、片场用户发送礼物，升级经验
    if (webUser.getUserType() != GlobalConstants.USER_TYPE_FAMOUS && webUser.getUserType() != GlobalConstants.USER_TYPE_STAR && webUser.getUserType() != GlobalConstants.USER_TYPE_SITE) {
      if (rebalanceVo.getExp() > 0) {
        //获取用户经验，如果升级则im通知前端
        ResultBean<UserLevelChangeVo> resultBean = webUserService.userLevelOprate(rebalanceVo.getFromId(), rebalanceVo.getExp());
        if (resultBean == null || resultBean.getCode() != ResultCode.SUCCESS.get_code()) {
          throw new DataIllegalException("等级更新异常！userId=" + rebalanceVo.getFromId());
        }
        if (resultBean.getData().getIsChange() == 1) {
          logger.info("用户={}经验升级", webUser.getUserId());
          privateMessageService.dealImMessage(rebalanceVo, ImCustomMsgEnum.UserLevelMsg_2.getType(), ImCustomMsgEnum.UserLevelMsg_2.getMsg(), webUser, resultBean.getData().getUserLevel());
        }
      }
    }
  }

  /**
   * 处理主播账目
   *
   * @param rebalanceVo
   * @param hefanNum    盒饭数
   * @param webUser     送礼人
   * @return Exception
   * @throws
   * @author wangchao
   * @create 2016/11/3 18:54
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  private void dealAnchorDetail(RebalanceVo rebalanceVo, Integer hefanNum, WebUser webUser) throws Exception {
    /*//区分真实和虚拟用户
    boolean flag = webUser.getUserType() != GlobalConstants.USER_TYPE_FLASE;
    if (rebalanceVo.getSource() != GlobalConstants.SOURCE_TYPE_CLUB) {
      //直播日志
      LiveLog liveLog = new LiveLog();
      liveLog.setLiveUuid(rebalanceVo.getLiveUuid());
      liveLog.setUserId(rebalanceVo.getToId());

      if (flag) {
        liveLog.setTicketCount((long) hefanNum);
        liveLog.setFalseTicketCount(0L);
      } else {
        liveLog.setTicketCount(0L);
        liveLog.setFalseTicketCount((long) hefanNum);
      }
      //更新直播盒饭收入
      int i = liveLogService.updateLiveLogForRebalance(liveLog);
      if (i != 1) {
        throw new DataIllegalException(String.format("保存本次直播信息异常数据回滚%s", JSON.toJSONString(liveLog)));
      }

      logger.debug("直播间盒饭数");

      LiveRoom liveRoom = new LiveRoom();
      liveRoom.setTicketHistory((long) hefanNum);
      liveRoom.setUserId(rebalanceVo.getToId());
      int id = liveRoomService.updateLiveRoomForRebalance(liveRoom);
      if (id != 1) {
        throw new DataIllegalException(String.format("更新主播的固定直播间信息异常数据回滚%s", JSON.toJSONString(liveLog)));
      }
    }
    logger.info(  "维护主播{}统计月表",rebalanceVo.getToId());
    anchorTicketMonthService.updateAnchorMonth(rebalanceVo, hefanNum, flag);*/

  }

  /**
   * 账户扣费明细、主播收入明细、处理扣费用户经验
   * @description 只有发送扣费行为及price>0 才触发
   * @param rebalanceVo
   * @param hefanNum
   * @param fanPiaoNum
   * @param webUser
   * @throws Exception
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void dealAccountDetail(RebalanceVo rebalanceVo, int hefanNum, int fanPiaoNum, WebUser webUser) throws Exception{
    logger.info("用户有扣费金额={}，记录消费和收入记录rebalanceVo={}", fanPiaoNum, JSON.toJSONString(rebalanceVo));
    if (fanPiaoNum > 0) {
      //扣费明细
      expendService.saveExpend(rebalanceVo, fanPiaoNum);
      //主播收入明细
      inComeService.saveWebIncome(rebalanceVo, hefanNum);
      //处理扣费用户经验
      dealAccountExp(rebalanceVo, webUser);
    }
  }

}